package com.yiwei.jmx.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.yiwei.jmx.R;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.CheckCodeBean;
import com.yiwei.jmx.api.bean.LoginBean;
import com.yiwei.jmx.api.bean.RegisterBean;
import com.yiwei.jmx.api.bean.SmsSendBean;
import com.yiwei.jmx.base.BaseActivity;
import com.yiwei.jmx.constant.UserInfoGlobal;
import com.yiwei.jmx.event.LoginSuccessEvent;
import com.yiwei.jmx.util.MD5;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.UI;
import com.yiwei.jmx.util.Util;
import com.yiwei.jmx.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class LoginTotalActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.btn_wechat)
    TextView btnWechat;
    @BindView(R.id.edit_user)
    EditText editUser;
    @BindView(R.id.btn_account_clear)
    ImageView btnAccountClear;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.btn_send_code)
    TextView btnSendCode;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.btn_login_by_pass)
    TextView btnLoginByPass;
    @BindView(R.id.btn_agree)
    TextView btnAgree;

    private String phone = "";
    private boolean isNewUser;
    private Unbinder unbiner;
    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            try {
                btnSendCode.setEnabled(false);
                btnSendCode.setText((millisUntilFinished / 1000) + "s重新获取");
//                btnSendCode.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray));
            } catch (Resources.NotFoundException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFinish() {
            resetBtn();
        }
    };


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        btnSendCode.setEnabled(true);
        btnSendCode.setText("重新发送");
    }

    @OnTextChanged({R.id.edit_user, R.id.edit_code})
    void afterTextChanged(Editable s) {
        if (TextUtils.isEmpty(UI.toString(editUser)) || TextUtils.isEmpty(UI.toString(editCode))) {
            btnSubmit.setSelected(false);
        }else {
            btnSubmit.setSelected(true);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_total);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(LoginSuccessEvent msg) {
        finish();
    }

    public void getSmsSend(String mobile) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        SmsSendBean bean = new SmsSendBean();
        bean.mobile = mobile;
        bean.type = "sms";
        Api.api_service.getSmsSend(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    timer.start();
                    phone = mobile;
                    if (result.data.new_mobile == 1) {
                        isNewUser = true;
                    } else {
                        isNewUser = false;
                    }
                });
    }

    public void getCheckCode(String account, String verify_code) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        CheckCodeBean bean = new CheckCodeBean();
        bean.mobile = account;
        bean.verify_code = verify_code;
        Api.api_service.getCheckCode(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Intent intent = new Intent(this, RegisterActivity.class);
                    intent.putExtra("ctoken", result.data.ctoken);
                    intent.putExtra("account", account);
                    startActivity(intent);
                    finish();
                });
    }

    public void getLogin(String account, String verify_code) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        LoginBean bean = new LoginBean();
        bean.account = account;
        bean.verify_code = verify_code;
        Api.api_service.getLogin(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    UserInfoGlobal.login();
                    ToastUtil.makeText(this, "登录成功");
                    finish();
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_back, R.id.btn_wechat, R.id.btn_account_clear, R.id.btn_send_code, R.id.btn_submit, R.id.btn_login_by_pass, R.id.btn_agree})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_wechat:
                Util.startActivity(this, WechatChatActivity.class);
                break;
            case R.id.btn_account_clear:
                editUser.setText("");
                break;
            case R.id.btn_send_code:
                if (UI.toString(editUser).length() != 11) {
                    ToastUtil.makeText(this, "请输入正确的手机号");
                    return;
                }
                phone = "";
                isNewUser = false;
                getSmsSend(UI.toString(editUser));
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(UI.toString(editUser))) {
                    ToastUtil.makeText(this, "账号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editCode))) {
                    ToastUtil.makeText(this, "验证码不能为空");
                    return;
                }
                if (UI.toString(editUser).equals(phone)) {
                    if (isNewUser) {
                        getCheckCode(UI.toString(editUser), UI.toString(editCode));
                    } else {
                        getLogin(UI.toString(editUser), UI.toString(editCode));
                    }
                } else {
                    getLogin(UI.toString(editUser), UI.toString(editCode));
                }

                break;
            case R.id.btn_login_by_pass:
                Util.startActivity(this, LoginByPassActivity.class);
                break;
            case R.id.btn_agree:
                break;
        }
    }
}
